/*
 * @Author: 张小平
 * @Date:   2025-05-01
 * @Email:  qqshuqian@163.com
 * @Copyright © 2024 aseyun. All rights reserved.
 */
import {validatenull} from './validate'
import Base64 from 'crypto-js/enc-base64';

import * as CryptoJS from "crypto-js";

import request from '@/framework-core/axios';
import website from '@/framework-core/config/website';


import store from '@/framework-core/store/';


export const downloadFile = (url, fileName) => {
    let token = store.getters.token
    let apiUrl = url.indexOf("http") >= 0 ? url : website.baseUrl + url;
    const headers = new Headers();
    headers.append(website.Authorization, token); // 设置token
    // 发起 Fetch 请求
    fetch(apiUrl, {
        method: 'GET',
        headers: headers,
    }).then(res => res.blob()).then(blob => {
        const a = document.createElement('a');
        a.href = window.URL.createObjectURL(blob);
        a.download = fileName; // 设置下载文件名
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }).catch(error => console.error('下载失败：', error));
};


//表单序列化
export const serialize = data => {
    let list = [];
    Object.keys(data).forEach(ele => {
        list.push(`${ele}=${data[ele]}`)
    })
    return list.join('&');
};

export const removeEmptyFields = obj => {
    return Object.keys(obj)
        .filter(key => obj[key] !== null && obj[key] !== undefined && obj[key] !== '')
        .reduce((result, key) => {
            result[key] = obj[key];
            return result;
        }, {});
}


export const loadPdfScript = () => {
    let list = [];
    list.push('https://cdn.staticfile.net/jspdf/1.5.3/jspdf.min.js')
    loadJsScript(list);
}

export const loadxlsxScript = () => {
    let list = [];
    list.push('https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js')
    list.push('https://cdn.staticfile.org/FileSaver.js/2014-11-29/FileSaver.min.js')
    loadJsScript(list);
}


export const loadEChartsScript = () => {
    let list = [];
    //list.push('https://cdnjs.cloudflare.com/ajax/libs/echarts/4.3.0/echarts.min.js')
     list.push('https://cdnjs.cloudflare.com/ajax/libs/echarts/6.0.0/echarts.min.js')
    loadJsScript(list);
}

export const loadAMapScript = () => {
    let list = [];
    list.push('https://webapi.amap.com/maps?v=2.0&key=9b88d15854bf57e89ffefbcfc1b3b7ee&plugin=AMap.PlaceSearch,AMap.Geocoder')
    list.push('https://webapi.amap.com/ui/1.1/main.js?v=1.0.11')
    loadJsScript(list);
}


export const loadJsScript = (list) => {
    for (let i = 0; i < list.length; i++) {
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = list[i];
        document.body.appendChild(script);
    }
}


export const getObjType = obj => {
    var toString = Object.prototype.toString;
    var map = {
        '[object Boolean]': 'boolean',
        '[object Number]': 'number',
        '[object String]': 'string',
        '[object Function]': 'function',
        '[object Array]': 'array',
        '[object Date]': 'date',
        '[object RegExp]': 'regExp',
        '[object Undefined]': 'undefined',
        '[object Null]': 'null',
        '[object Object]': 'object'
    };
    if (obj instanceof Element) {
        return 'element';
    }
    return map[toString.call(obj)];
};
/**
 * 对象深拷贝
 */
export const deepClone = data => {
    var type = getObjType(data);
    var obj;
    if (type === 'array') {
        obj = [];
    } else if (type === 'object') {
        obj = {};
    } else {
        //不再具有下一层次
        return data;
    }
    if (type === 'array') {
        for (let i = 0, len = data.length; i < len; i++) {
            obj.push(deepClone(data[i]));
        }
    } else if (type === 'object') {
        for (let key in data) {
            obj[key] = deepClone(data[key]);
        }
    }
    return obj;
};
/**
 * 设置灰度模式
 */
export const toggleGrayMode = (status) => {
    if (status) {
        document.body.className = document.body.className + ' grayMode';
    } else {
        document.body.className = document.body.className.replace(' grayMode', '');
    }
};
/**
 * 设置主题
 */
export const setTheme = (name) => {
    document.body.className = name;
}

//防抖
export const debounce = function (fn, delay) {
    let timer = null;
    return function () {
        let content = this;
        let args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            fn.apply(content, args);
        }, delay);
    };
};

/**
 * 加密处理
 */
export const encryption = (params) => {
    let {
        data = {},
        type,
        param,
        key
    } = params;

    if (!type) {
        type = 'aes'
    } else {
        type = type.toLocaleString();
    }
    let result = JSON.parse(JSON.stringify(data));
    if (type == 'base64') {
        param.forEach(ele => {
            result[ele] = Base64.stringify(result[ele]);
        })
    } else if (type == 'aes') {
        param.forEach(ele => {
            // result[ele] = sha256(result[ele], key)
            var data = result[ele];
            //key = CryptoJS.enc.Latin1.parse(key);
            var iv = key;
            // 加密
            var encrypted = CryptoJS.AES.encrypt(data, key, {
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            });
            result[ele] = encrypted.toString();
        })
    }
    return result;
};


/**
 * 浏览器判断是否全屏
 */
export const fullscreenToggel = () => {
    if (fullscreenEnable()) {
        exitFullScreen();
    } else {
        reqFullScreen();
    }
};
/**
 * esc监听全屏
 */
export const listenfullscreen = (callback) => {
    function listen() {
        callback()
    }

    document.addEventListener("fullscreenchange", function () {
        listen();
    });
    document.addEventListener("mozfullscreenchange", function () {
        listen();
    });
    document.addEventListener("webkitfullscreenchange", function () {
        listen();
    });
    document.addEventListener("msfullscreenchange", function () {
        listen();
    });
};
/**
 * 浏览器判断是否全屏
 */
export const fullscreenEnable = () => {
    var isFullscreen = document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen
    return isFullscreen;
}

/**
 * 浏览器全屏
 */
export const reqFullScreen = () => {
    if (document.documentElement.requestFullScreen) {
        document.documentElement.requestFullScreen();
    } else if (document.documentElement.webkitRequestFullScreen) {
        document.documentElement.webkitRequestFullScreen();
    } else if (document.documentElement.mozRequestFullScreen) {
        document.documentElement.mozRequestFullScreen();
    }
};
/**
 * 浏览器退出全屏
 */
export const exitFullScreen = () => {
    if (document.documentElement.requestFullScreen) {
        document.exitFullScreen();
    } else if (document.documentElement.webkitRequestFullScreen) {
        document.webkitCancelFullScreen();
    } else if (document.documentElement.mozRequestFullScreen) {
        document.mozCancelFullScreen();
    }
};
/**
 * 递归寻找子类的父类
 */

export const findParent = (menu, id) => {
    for (let i = 0; i < menu.length; i++) {
        if (menu[i].children.length != 0) {
            for (let j = 0; j < menu[i].children.length; j++) {
                if (menu[i].children[j].id == id) {
                    return menu[i];
                } else {
                    if (menu[i].children[j].children.length != 0) {
                        return findParent(menu[i].children[j].children, id);
                    }
                }
            }
        }
    }
};
/**
 * 判断2个对象属性和值是否相等
 */

/**
 * 动态插入css
 */

export const loadStyle = url => {
    const link = document.createElement('link');
    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.href = url;
    const head = document.getElementsByTagName('head')[0];
    head.appendChild(link);
};
/**
 * 判断路由是否相等
 */
export const diff = (obj1, obj2) => {
    delete obj1.close;
    var o1 = obj1 instanceof Object;
    var o2 = obj2 instanceof Object;
    if (!o1 || !o2) { /*  判断不是对象  */
        return obj1 === obj2;
    }

    if (Object.keys(obj1).length !== Object.keys(obj2).length) {
        return false;
        //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如：数组返回下表：let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
    }

    for (let attr in obj1) {
        var t1 = obj1[attr] instanceof Object;
        var t2 = obj2[attr] instanceof Object;
        if (t1 && t2) {
            return diff(obj1[attr], obj2[attr]);
        } else if (obj1[attr] !== obj2[attr]) {
            return false;
        }
    }
    return true;
}
/**
 * 根据字典的value显示label
 */
export const findByvalue = (dic, value) => {
    let result = '';
    if (validatenull(dic)) return value;
    if (typeof (value) == 'string' || typeof (value) == 'number' || typeof (value) == 'boolean') {
        let index = 0;
        index = findArray(dic, value);
        if (index != -1) {
            result = dic[index].label;
        } else {
            result = value;
        }
    } else if (value instanceof Array) {
        result = [];
        let index = 0;
        value.forEach(ele => {
            index = findArray(dic, ele);
            if (index != -1) {
                result.push(dic[index].label);
            } else {
                result.push(value);
            }
        });
        result = result.toString();
    }
    return result;
};
/**
 * 根据字典的value查找对应的index
 */
export const findArray = (dic, value) => {
    for (let i = 0; i < dic.length; i++) {
        if (dic[i].value == value) {
            return i;
        }
    }
    return -1;
};
/**
 * 生成随机len位数字
 */
export const randomLenNum = (len, date) => {
    let random = '';
    random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len ? len : 4);
    if (date) random = random + Date.now();
    return random;
};
/**
 * 打开小窗口
 */
export const openWindow = (url, title, w, h) => {
    // Fixes dual-screen position                            Most browsers       Firefox
    const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left
    const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top

    const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width
    const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height

    const left = ((width / 2) - (w / 2)) + dualScreenLeft
    const top = ((height / 2) - (h / 2)) + dualScreenTop
    const newWindow = window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left)

    // Puts focus on the newWindow
    if (window.focus) {
        newWindow.focus()
    }
}


export const getScreen = (isCollapse) => {
    if (document.body.clientWidth <= 768) {
        return !isCollapse
    } else {
        return isCollapse
    }
}


export const doPermissions = (menus, map) => {
    menus.forEach(ele => {

        if (ele.type == 1) {
            if (ele.checked == true) {
                map.push(ele.authority);
            }
            if (ele.children) {
                return doPermissions(ele.children, map);
            }
        }
    })
    return map;
}

export const doMenu = (menus, map) => {
    menus.forEach(ele => {

        var node = {}
        node.id = ele.id;
        node.checked = ele.checked;
        node.open = ele.open;
        node.parentId = ele.parentId;
        node.groupTag = ele.groupTag;
        node.name = ele.name;
        node.appKey = ele.appKey;
        node.icon = ele.icon;
        node.path = ele.path;
        node.type = ele.type;
        node.sort = ele.sort;
        node.authority = ele.authority;
        node.target = ele.target;
        node.login = ele.login;
        if (ele.type == 0) {
            node.component = ele.component;
            node.nav = ele.nav;
            node.meta = ele.meta;
            node.hide = ele.hide;
            node.style = ele.style;
        }
        node.children = [];
        if (ele.type == 0) {
            if (ele.children) {
                map.push(node);
                node.children = doMenu(ele.children, node.children);
            } else {
                if (ele.checked == true || ele.nav === 0) {
                    map.push(node);
                }
            }
        }
    })
    return map;
}


export const getMenu = (menus, key) => {
    for (let i = 0; i < menus.length; i++) {
        if (!menus[i].checked == true) {
            continue;
        }
        if (menus[i].path == key) {
            return menus[i];
        } else {
            if (menus[i].children) {
                var path = getMenu(menus[i].children, key)
                if (path) {
                    return path;
                }
            }
        }
    }
    return null;
}

export const convertDic = (menus, map, valueToString) => {
    menus.forEach(node => {
        const d = {
            value: node.id,
            label: node.name,
            children: []
        };
        if (valueToString) {
            d.value = d.value + "";
        }
        map.push(d);
        if (node.children) {
            return convertDic(node.children, d.children, valueToString);
        }
    })
    return map;
}

// 表单字典默认是字符串，系统二开默认如果是数字字符串则显示数字[已经优化，不做修改又业务自行处理，数字类型的将dicCodeType 设置成1]
// 此处兼容移动移动端使用的是text
export const convertVantDic = (dics) => {
    dics.forEach(node => {
        node.value = node.value
        node.text = node.label
    })
}


export const getObjDeepValue = (obj, keys) => {
    return getObjDeepValueList(obj, keys.split("."));
}

export const getObjDeepValueList = (obj, keys) => {
    if (!obj) {
        return obj;
    }
    if (keys.length === 1) {
        return obj[keys[0]];
    }
    return getObjDeepValueList(obj[keys[0]], keys.slice(1));
}

export const convertPcComm = (column) => {

    if (column.dicUrl) {
        if (!column.dicUrl.startsWith('http')) {
            column.dicUrl = website.baseUrl + column.dicUrl;
            if (!column.dicFormatter) {
                column.dicFormatter = (res) => {
                    return res.data.data
                }
            }
        }
        columnCallApi(column);
    } else {
        if (column.dicData) {
            convertVantDic(column.dicData)
        }
    }


    // 校验
    if (column.pattern && !column.disabled) {
        if (!column.rules) {
            column.rules = []
        }
        const commValidate = function (pattern, msg) {
            return function (rule, value, callback) {
                //例：触发位于表单中，存在多行数据时
                //取得所在行数据
                let rowIndex = rule.field.replace(/[^0-9]/ig, "");
                let patt = new RegExp(pattern, 'g');
                if (!patt.test(value)) {
                    callback(new Error(msg || '格式错误'));
                } else {
                    callback();
                }
            };
        };


        let ruleItem = {
            validator: commValidate(column.pattern, column.patternMsg),
            trigger: column.patternEvent || "blur"
        };
        column.rules.push(ruleItem);
    }

    var isMobileTemp = window.innerWidth < 800;
    isMobileTemp = window.isMobile || isMobileTemp;
    if (column.type == "table") {
        // column.children.grid = isMobileTemp;
        // column.children.gridSpan = 24;
        if (column.onLoadJs) {
            try {
                //column.onLoad = eval(column.onLoadJs)
                window.request = request;
                window.getObjDeepValue = getObjDeepValue;
                column.onLoad = new Function('return ' + column.onLoadJs)();

                // var func = new Function('return ' + this.viewFormData.option.beforJs)(); // 将字符串转换成函数
                // var $that = this;
                // var result = func.apply($that, [this.viewFormData.form]); // 传入参数执行函数
                //
            } catch (e) {
                console.error(e)
            }
        }

        if (column.formatterJs) {
            try {
                column.formatter = eval(column.formatterJs)
            } catch (e) {
                console.error(e)
            }
        }
    }

}

export const convertAvueByColumn = (column, isMobileTemp, print, printOneRow) => {
    if (print) {
        if (!!column.noprint) {
            column.display = false;
        }
        if (column.type == "group") {
            column.arrow = false;
            //column.collapse = true;
        }
        if (column.type == "JrSignature" || column.type == "userChoose" || column.type == "roleTreeChoose" || column.type == "orgTreeChoose") {
            column.disabled = true;
        }
        if (printOneRow) {
            column.span = 24;
            column.labelWidth = 200;
        }
    }

    convertPcComm(column);
    if (isMobileTemp) {
        convertVantMobileColumn(column);
    }
    if (column.children) {
        if (column.children.column) {
            column.children.column.forEach((column22) => {
                convertAvueByColumn(column22, isMobileTemp)
            });
        } else {
            if (column.children.length > 0) {
                column.children.forEach((children) => {
                    children.column.forEach((column33) => {
                        convertAvueByColumn(column33, isMobileTemp)
                    });
                });
            }
        }
    }
}


export const convertVantMobile = (option, print) => {

    if (print) {
        option.detail = print;
        option.submitBtn = false;
        option.emptyBtn = false;

        // var innerWidth = window.innerWidth;
        // var printWidth = 210 * 3.779527559055118;
        // option.bgMargin = ((innerWidth - printWidth)*50)/innerWidth;

        option.bgMargin = 0;
    }
    var isMobileTemp = window.innerWidth < 800;
    isMobileTemp = window.isMobile || isMobileTemp;
    if (window.isMobile || isMobileTemp) {
        option.dialogFullscreen = true;
        option.grid = true;
        option.gridSpan = 24;
        option.searchShow = true;
        option.searchIcon = true;
        option.searchIndex = 1;
        option.labelSuffix = " ";
    }

    option.column.forEach((column) => {
        convertAvueByColumn(column, isMobileTemp, print, !!option.printOneRow)
    });

    if (option.group) {
        option.group.forEach((groupItem) => {
            if (groupItem.column) {
                groupItem.column.forEach((column22) => {
                    convertAvueByColumn(column22, isMobileTemp, print, !!option.printOneRow)
                });
            }
        });
    }


    if (option.group) {
        option.group.forEach((groupItem) => {
            if (groupItem.isGird) {
                // groupItem.component = "form-table";
                // groupItem.className = ' form-gird';
                // groupItem.type = "dynamic";
                // groupItem.display = false;
                // groupItem.display = true;

                groupItem.display = false;
                var column = {};
                column.component = "form-table";
                column.type = "group";
                column.span = 24;
                column.className = ' form-gird';
                column.label = groupItem.label;
                column.prop = groupItem.prop;
                column.children = deepClone(groupItem.column);
                option.column.push(column);
                groupItem = null;
            }
        });
    }
}

export const convertVantMobileColumn = (column) => {
    var avantType = getTypeExchange(column);
    if (column.labelWidth > 120) {
        column.labelWidth = 120
    }
    if (avantType && avantType.startsWith('avant-')) {
        column.component = avantType;
        column.type = avantType;
        column.span = 24;

        if (column.display === undefined) {
            column.display = true;
        }
        column.className = column.className + ' noShowLable';
    }

    if (column.type == "dynamic") {
        column.grid = true;
        column.gridSpan = 24;
        if (column.children) {
            column.children.grid = true;
            column.children.gridSpan = 24;
        }
    }

    if (column.dicData) {
        convertVantDic(column.dicData)
    }

}

/**
 * 数据赋值
 * @param data
 * @param formData，表单数据 @{{}}
 * @param query     url 数据 {{}}
 * @param params    静态数据 {@{}}
 * @returns {*}
 */
export const convertHtmlByParam = (data, formData, query, params) => {
    if (!data) {
        return data;
    }
    let content = data;
    if (formData) {
        content = data.replace(/@{{(\w+)}}/g, (match, key) => formData ? (formData[key] || "") : "");
    }
    if (query) {
        content = content.replace(/{{(\w+)}}/g, (match, key) => query[key] || "");
    }
    if (params) {
        content = content.replace(/{@{(\w+)}}/g, (match, key) => params[key] ? (params[key].pvalue || "") : "");
    }

    if (content.indexOf("${now()}") >= 0) {
        content = content.replace("${now()}", timeToString(new Date(), 'yyyy-MM-dd hh:mm:ss'));
    }
    return content;
}

export const columnCallApi = (column, query, key, callback) => {

    let urlParams = new URLSearchParams();
    let pdata = {};
    if(obj.constructor === Object){
        pdata = query;
    }else{
        if (query) {
            urlParams.append('searchKeyword', query);
        }
    }

    var dicUrl = column.dicUrl;
    if (!dicUrl) {
        return;
    }

    let url = dicUrl.includes('?') ? dicUrl + '&' + urlParams.toString() : dicUrl + '?' + urlParams.toString();
    if (!dicUrl.startsWith('http')) {
        url = website.baseUrl + url;
    }
    if (url.indexOf("{{") >= 0 || url.indexOf("{@{") >= 0) {
        if (key) {
            url = url.replace("{{key}}", key);
        } else {
            return
        }
    }
    let httpOption = {
        method: column.dicMethod,
        url,
        data: pdata
    };

    var contentType = column.contentType;
    if (contentType) {
        httpOption.headers = {'Content-Type': contentType};
    }

    var $column = column;
    // 确保request始终返回一个promise
    Promise.resolve(request(httpOption))
        .then((res) => {
            // $that.loading = false;
            var listData = [];
            if ($column.dicFormatterJs) {
                $column.dicFormatter = eval($column.dicFormatterJs);
                listData = $column.dicFormatter(res);
            } else {
                listData = res.data.data.data;
            }
            if (!listData) {
                listData = [];
            }
            // 检查res.data是否是一个数组
            let arr = [];
            if (Array.isArray(listData) && listData.length) {
                listData.forEach((e) => { // 使用forEach代替map
                    if (e[$column.props.value]) {
                        e[$column.props.value] = e[$column.props.value] + ""
                    }
                    arr.push({
                        ...e,
                        label: e[$column.props.label || 'label'] + "",
                        value: e[$column.props.value || 'value'] + "",
                    });
                });
            } else {

            }
            $column.dicData = arr;
            if (callback) {
                callback(arr);
            }
            // console.log($column)
        })
        .catch((error) => {
            // $that.$message.error(error.msg || 'An error occurred.');
        });
}


export const httpCallApi=async (column, query) => {
    let urlParams = new URLSearchParams();

    let dicUrl = column.dicUrl;
    if (!dicUrl) {
        return [];
    }
    let url = dicUrl.includes('?') ? dicUrl + '&' + urlParams.toString() : dicUrl + '?' + urlParams.toString();
    if (!dicUrl.startsWith('http')) {
        url = website.baseUrl + url;
    }
    let httpOption = {
        method: column.dicMethod,
        url,
        data: query
    };

    let contentType = column.contentType;
    if (contentType) {
        httpOption.headers = {'Content-Type': contentType};
    }

    var $column = column;
    // 确保request始终返回一个promise
    let listData = [];
    await request(httpOption).then((res) => {
        // $that.loading = false;
        if ($column.dicFormatterJs) {
            $column.dicFormatter = eval($column.dicFormatterJs);
            listData = $column.dicFormatter(res);
        } else {
            listData = res;
        }

        // console.log($column)
    })
    return listData
}

export const getTypeExchange = (column) => {
    if (column.labelWidth == 120) {
        column.labelWidth = 90
    }

    switch (column.type) {
        case 'input':
            return 'avant-input'
        case 'number':
            return 'avant-number'

        // case 'password':
        //     return 'avant-input'
        // case 'textarea':
        //     return 'avant-input'
        // case 'number':
        //     return 'avant-number'
        // case 'map':
        //     return 'avant-map'
        case 'radio':
            return 'avant-radio'
        case 'checkbox':
            return 'avant-checkbox'
        case 'select':
            if (column.multiple) {
                return 'select';
            }
            if ((column.cascader && column.cascader.length > 0) || column.parentProp) {
                return 'avant-cascader'
            }

            return 'avant-picker'
        case 'cascader':
            return 'avant-cascader'
        // case 'upload':
        //     return 'avant-upload'

        case 'year':
            column.dateType = ['year'];
            column.dateformat = "yyyy";
            return 'avant-date';
        case 'week':
            column.dateformat = "week";
            return 'avant-date';
        case 'month':
            column.dateType = ['year', 'month'];
            column.dateformat = "yyyyMM";
            return 'avant-date';
        case 'date':
            column.dateformat = "yyyyMMdd";
            return 'avant-date';
        case 'datetime':
            return 'avant-datetime'
        case 'datetimerange':
            return 'avant-datetimerange'
        case 'daterange':
            column.dateType = ['year', 'month', 'day'];
            column.dateformat = "yyyyMMdd";
            return 'avant-daterange'
        case 'time':
            return 'avant-time'
        case 'timerange':
            return 'avant-timerange'
        case 'tab':
            return 'avant-tabbar'
        // case 'switch':
        //     return 'avant-switch'
        // case 'rate':
        //     return 'avant-rate'
        // case 'slider':
        //     return 'avant-slider'
        // case 'dynamic':
        //     return 'avant-dynamic'
        // case 'ueditor':
        //     return 'avant-ueditor'

    }
    return column.type
}


/**
 * 获取年
 * @param date
 * @returns {number}
 */
export const getCurYear = (date) => {
    if (!date) {
        date = new Date();
    }
    return date.getFullYear();
}

/**
 * 获取月
 * @param date
 * @returns {number}
 */
export const getCurMonth = (date) => {
    if (!date) {
        date = new Date();
    }
    return date.getMonth();
}

export const timestampToTime = (timestamp) => {
    if (timestamp > 10000000000) {
        return new Date(timestamp);
    }
    return new Date(timestamp * 1000);
}

export const timeToString = (date, fmt) => {
    var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (let k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

export const hasMobile = () => {
    let isMobile = false;

    if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
        // console.log('移动端');
        isMobile = true;
    }
    // debugger
    if (document.body.clientWidth < 800) {
        isMobile = true;
    }
    return isMobile
}

export const getUuid = () => {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (let i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23];
    var uuid = s.join("");
    return uuid;
}


//时间戳转换方法 年-月-日   dateValue:时间戳数字
export function formatDate(dateValue, type) {
    if (!dateValue) {
        return ""
    }
    var date = new Date(dateValue);
    var YY = date.getFullYear();
    var MM = '-' + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    var DD = '-' + (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
    var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
    var mm = ':' + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
    var ss = ':' + (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    var result = ""
    switch (type) {
        case 6:
            result = YY + MM + DD + " " + hh + mm + ss;
            break;
        case 5:
            result = YY + MM + DD + " " + hh + mm;
            break;
        case 4:
            result = YY + MM + DD + " " + hh + ':00';
            break;
        case 3:
            result = YY + MM + DD;
            break;
        case 2:
            result = YY + MM;
            break;
        case 1:
            result = hh + mm + ss;
            break;
        default:
            result = YY + MM + DD + " " + hh + mm + ss;
    }
    return result
}

//时间戳转换方法 年-月-日   dateValue:时间戳数字
export function formatDateVant(dateValue, type) {
    if (!dateValue) {
        return ""
    }
    var date = new Date(dateValue);
    var YY = date.getFullYear();
    var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
    var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
    var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
    // var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    var result = ""
    switch (type) {
        case 6:
            result = MM + "-" + DD;
            break;
        case 5:
            result = YY + "-" + MM + "-" + DD + " " + hh + ":" + mm;
            break;
        case 4:
            result = YY + "-" + MM + "-" + DD + " " + hh + ':00';
            break;
        case 3:
            result = YY + "-" + MM + "-" + DD;
            break;
        case 2:
            result = YY + "-" + MM;
            break;
        case 1:
            result = hh + ":" + mm;
            break;
        default:
            result = YY + "-" + MM + "-" + DD
    }
    return result
}


export function formatDateToVants(dates, type) {
    var result = '';
    if (!dates) {
        return "";
    }
    switch (type) {
        case "week":
            result = dates[0] + "-" + dates[1] + "-" + dates[2];
            break;
        case "yyyy":
            result = dates[0];
            break;
        case "yyyyMM":
            result = dates[0] + "-" + dates[1];
            break;
        case "yyyyMMdd":
            result = dates[0] + "-" + dates[1] + "-" + dates[2];
            break;
        case "yyyyMMdd hh:mm":
            result = dates[0] + "-" + dates[1] + "-" + dates[2] + " " + dates[3] + ':' + dates[4];
            break;
        default:
            result = dates[0] + "-" + dates[1] + "-" + dates[2];
    }
    return result
}

export function getWeekNumber(endDate) {
    if (!endDate) {
        return ""
    }
    if (!endDate.getTime()) {
        return ""
    }
    //本年的第一天
    var beginDate = new Date(endDate.getFullYear(), 0, 1);
    //星期从0-6,0代表星期天，6代表星期六
    var endWeek = endDate.getDay() + 1;
    //if (endWeek == 0) endWeek = 7;
    var beginWeek = beginDate.getDay() + 1;
    //if (beginWeek == 0) beginWeek = 7;
    //计算两个日期的天数差
    var millisDiff = endDate.getTime() - beginDate.getTime();
    var dayDiff = Math.floor((millisDiff + (beginWeek - endWeek) * (24 * 60 * 60 * 1000)) / 86400000);
    return endDate.getFullYear() + ' 第 ' + (Math.ceil(dayDiff / 7) + 1) + "周";

}

export function formatToDateVants(date, type) {
    var dates = [];
    if (!date) {
        dates.push("");
        dates.push("");
        dates.push("");
        dates.push("");
        dates.push("");
        dates.push("");
        return dates;
    }
    if (typeof date === 'string') {
        date = new Date(date);
    }

    var YY = date.getFullYear();
    var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
    var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
    var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
    var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());


    switch (type) {
        case "week":
            dates.push(YY + '');
            dates.push(MM);
            dates.push(DD);
            //return  getWeekNumber( date);
            break;
        case "yyyy":
            dates.push(YY + '');
            break;
        case "yyyyMM":
            dates.push(YY + '');
            dates.push(MM);

            break;
        case "yyyyMMdd":
            dates.push(YY + '');
            dates.push(MM);
            dates.push(DD);
            break;
        case "yyyyMMdd hh:mm":
            dates.push(YY + '');
            dates.push(MM);
            dates.push(DD);
            dates.push(hh);
            dates.push(mm);
            break;
        case "yyyyMMdd hh:mm:ss":
            dates.push(YY + '');
            dates.push(MM);
            dates.push(DD);
            dates.push(hh);
            dates.push(mm);
            dates.push(ss);
            break;
        case "hhmm":
            dates.push(hh);
            dates.push(mm);
            break;
        case "hhmmss":
            dates.push(hh);
            dates.push(mm);
            dates.push(ss);
            break;
        default:
            dates.push(YY + '');
            dates.push(MM);
            dates.push(DD);
    }


    return dates
}

/**
 * 转化成树
 * @param nodes 原始对象
 * @param map 新对象
 * @param otherMapings 特殊的映射
 * @returns {*}
 */
export const convertTree = (nodes, map,otherMapings) => {
    nodes.forEach(node => {
        const d = {
            id: node.id,
            label: node.name,
            children: [],
            code: node.code,
            name: node.name,
            parentId: node.parentId,
            value: node.id
        };
        if (otherMapings) {
            for (let [okey, ovalue] of otherMapings) {
                d[okey] = node[ovalue]
            }
        }
        map.push(d);
        if (node.children) {
            return convertTree(node.children, d.children, otherMapings);
        }
    })
    return map;
}

